package com.gitee.feizns.quickstart.ding.talk.event;

import com.dingtalk.open.app.api.GenericEventListener;
import com.dingtalk.open.app.api.message.GenericOpenDingTalkEvent;
import com.dingtalk.open.app.stream.protocol.event.EventAckStatus;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;

/**
 * 流列表事件侦听器
 * @author feizns
 * @since 2025/3/24
 */
@RequiredArgsConstructor
public class StreamEventListListener implements GenericEventListener {

    /**
     * 听众
     */
    private final List<GenericEventListener> listeners = new ArrayList<>();

    @Override
    public EventAckStatus onEvent(GenericOpenDingTalkEvent event) {
        listeners.forEach(listener -> listener.onEvent(event));
        return EventAckStatus.SUCCESS;
    }

    /**
     * 注册
     * @param listener 听者
     * @return {@link StreamEventListListener }
     */
    public StreamEventListListener register(GenericEventListener listener) {
        listeners.add(listener);
        return this;
    }

    /**
     * 注册
     * @param eventType 事件类型
     * @param listener 听者
     * @return {@link StreamEventListListener }
     */
    public StreamEventListListener register(String eventType, GenericEventListener listener) {
        listeners.add(event -> {
            if ( Objects.equals(event.getEventType(), eventType) )
                return listener.onEvent(event);
            return EventAckStatus.SUCCESS;
        });
        return this;
    }

    /**
     * 注册
     * @param eventPredicate 事件谓词
     * @param listener 听者
     * @return {@link StreamEventListListener }
     */
    public StreamEventListListener register(Predicate<GenericOpenDingTalkEvent> eventPredicate, GenericEventListener listener) {
        listeners.add(event -> {
            if ( eventPredicate.test(event) )
                return listener.onEvent(event);
            return EventAckStatus.SUCCESS;
        });
        return this;
    }

}
